package ArrayList;

import java.util.Arrays;

public class ArrayList {
    private int[] elem;
    private int usedSize;
    public static final int DEFAULT_SIZE = 10;
    public ArrayList() {
        this.elem=new int[5];
    }

    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }

    public int getSize() {
        return this.usedSize;
    }

    public void add(int data) {
        if(isFull()) {
            reListSize();
        }
        elem[usedSize] = data;
        usedSize++;
    }

    private int istoFind(int num) {
        for (int i = 0; i < this.usedSize; i++) {
            if(num == elem[i]) {
                return i;
            }
        }
        return -1;
    }

    private boolean isFull() {
        if(this.elem.length == this.usedSize) {
            return true;
        }
        return false;
    }

    private void reListSize() {
        this.elem = Arrays.copyOf(this.elem,2*elem.length);
    }

    private boolean cheak (int pos){
        if(pos<0 || pos >= usedSize) {
            return true;
        }
        return false;
    }

    public void add(int pos, int data) {
        if(isFull()) {
            reListSize();
        }
        if(cheak(pos)) {
            throw new ArrayListException("数组越界");
        }
        for (int i = this.usedSize-1; i >= pos ; i--) {
            elem[i+1]=elem[i];
        }
        elem[pos]=data;
        usedSize++;
    }

    public boolean contains(int toFind) {
        if(istoFind(toFind) >= 0) {
            return true;
        }
        return false;
    }

    public int indexOf(int toFind) {
        return istoFind(toFind);
    }
    public int get(int pos) {
        if(isFull()) {
            reListSize();
        }
        if(cheak(pos)) {
            throw new ArrayListException("下标越界");
        }
        return elem[pos];
    }
    public void set(int pos, int value) {
        if(isFull()) {
            reListSize();
        }
        if(cheak(pos)) {
            throw new ArrayListException("下标越界");
        }
        elem[pos] = value;
    }
    public void remove(int toRemove) {
        int pos = istoFind(toRemove);
        if(pos<0) {
            System.out.println("没有要删除的元素");
            return;
        }
        for (int i = pos; i < this.usedSize-1; i++) {
            elem[i]=elem[i+1];
        }
        this.usedSize--;
    }

    public void clear() {
        this.usedSize=0;
    }
}
